<?php
/**
 * Created by PhpStorm.
 *
 * Author : Traveler.
 * Time   : 2020/2/25 11:13
 * Company: Inner Mongolia Zhengzhi Network Technology Co., Ltd
 */

namespace app\admin\model;


use app\admin\BaseModel;

class StaffRole extends BaseModel
{
    /**
     * 数据表名称
     * @var string
     */
    protected $table = 'ibms_staff_role';

    /**
     * 查询字段
     * @var array
     */
    protected $query = [
        'id'      => '=',
        'name'    => 'like',
        'status'  => '=',
    ];

    /**
     * (静态)获取表格渲染数据
     * @param array $param     请求参数
     * @param bool  $isdeleted 删除标记
     * @return array
     */
    public static function getStaffRoleTable(array $param = [], bool $isdeleted = false)
    {
        $model  = new static;
        $where  = [['delete_time', $isdeleted ? '>' : '=', 0]];
        $filter = $model->filterParam($param, $where);

        return [
            'data'  => $model->where($filter['where'])->order('id')->page($filter['page'], $filter['limit'])->select(),
            'count' => $model->where($filter['where'])->count()
        ];
    }

    /**
     * (静态)获取所有有效的场所类型
     * @return \think\Collection
     */
    public static function getValidStaffRole()
    {
        $where   = ['status' => 1, 'delete_time' => 0];
        $visible = ['id', 'name', 'bgcolor', 'nodes'];

        return static::where($where)->visible($visible)->order('id')->select();
    }

    /**
     * (静态)获取权限节点(树形结构)
     * @param string $ids 当前角色的权限节点
     * @return array
     */
    public static function getRoleNode(string $ids = '')
    {
        $where   = ['status' => 1, 'delete_time' => 0];
        $visible = ['id', 'pid', 'name'];

        $nodes = explode(',', $ids);
        $menu = Menu::where($where)->visible($visible)->order('sort', 'ASC')->select()->toArray();

        // zTree 相关数据，这些数据也可以在前端操作，根据个人习惯自行决定
        foreach ($menu as &$v) {
            // 根据当前角色已有权限节点，设置默认勾选
            $v['checked'] = in_array($v['id'], $nodes);

            // 设置展开状态
            $v['open'] = 0 == $v['pid'];

            // 控制台节点
            if (1 == $v['id']) {
                $v['checked'] = true;
                $v['chkDisabled'] = true;
                $v['icon'] = '/static/lib/zTree_v3/css/zTreeStyle/img/diy/1_close.png';
            }
        }

        return generateTree($menu);
    }

    /**
     * (静态)获取权限标识
     * @param string $role_nodes 当前角色的权限节点
     * @return array
     */
    public static function getRoleFlag(?string $role_nodes)
    {
        $where = ['type' => 1, 'status' => 1, 'delete_time' => 0];
        $nodes = explode(',', $role_nodes);

        return Menu::where($where)->whereIn('id', $nodes)->order('sort', 'ASC')->column('flags');
    }
}